<?php

namespace Xin\Process;

use Xin\Support\Console\Printer;

trait InteractsWithDump
{

	/**
	 * @var bool
	 */
	protected $debug = true;

	/**
	 * @param mixed ...$data
	 * @return void
	 */
	protected function dump(...$data)
	{
		if (!$this->debug) {
			return;
		}

		Printer::log("[" . class_basename(static::class) . "]", ...$data);
	}

	/**
	 * @param mixed ...$data
	 * @return void
	 */
	protected function dumpInfo(...$data)
	{
		if (!$this->debug) {
			return;
		}

		Printer::info("\033[37m[" . class_basename(static::class) . "]\033[0m", ...$data);
	}

	/**
	 * @param mixed ...$data
	 * @return mixed
	 */
	protected function dumpInfoText(...$data)
	{
		return Printer::infoText(...$data);
	}

	/**
	 * @param ...$data
	 * @return void
	 */
	protected function dumpError(...$data)
	{
		//		if (!$this->debug) {
		//            return;
		//		}

		Printer::error("[" . class_basename(static::class) . "]", ...$data);
	}

	/**
	 * @param mixed ...$data
	 * @return mixed
	 */
	protected function dumpErrorText(...$data)
	{
		return Printer::errorText(...$data);
	}

	/**
	 * @param bool $debug
	 * @param callable|null $callback
	 * @return mixed
	 * @noinspection PhpUnhandledExceptionInspection
	 * @noinspection PhpDocMissingThrowsInspection
	 */
	public function useDumpDebug(bool $debug = true, callable $callback = null)
	{
		if (is_callable($callback)) {
			try {
				$oldDebug = $this->debug;
				$this->debug = $debug;
				$result = $callback($oldDebug);
			} catch (\Throwable $e) {
				/** @noinspection PhpDocMissingThrowsInspection */
				throw $e;
			} finally {
				$this->debug = $oldDebug;
			}

			return $result;
		} else {
			$this->debug = $debug;
		}
	}
}
